//
//  HomeViewController.m
//  HxgProject
//
//  Created by hxg on 2018/3/1.
//  Copyright © 2018年 XMYY-19. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeService.h"
#import "UIColor+HEX.h"
#import "UIButton+Extention.h"
#import "ResObject.h"

#import "PackageInfo.h"
#import <IQKeyboardReturnKeyHandler.h>

#define btnH 89.0f
#define btnW 125.0f

// 0代表不显示服务费 1代表显示服务费
#define isShowServiceMoney 1

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    IQKeyboardReturnKeyHandler *returnKeyHandler;
}

@property (nonatomic, strong) UITableView *borrowTableView;

@property (nonatomic, retain) NSIndexPath * selectedIndexPath;

// 借款1000的按钮
@property (nonatomic, strong)  UIButton *num1Btn;

// 借款2000的按钮
@property (nonatomic, strong)  UIButton *num2Btn;

// 额度1000的数据源
@property (nonatomic, strong) NSMutableArray *num1000Arr;

// 额度2000的数据源
@property (nonatomic, strong) NSMutableArray *num2000Arr;


@property (nonatomic, strong) UILabel *payMoneyLbl;

// 选中的数据源
@property (nonatomic, strong) NSMutableArray *selectedArr;


// 1000的服务费选项
@property (nonatomic, strong) NSArray *serviceMoney1000Arr;

// 2000的服务费选项
@property (nonatomic, strong) NSArray *serviceMoney2000Arr;

// 选中的服务费的数据源
@property (nonatomic, strong) NSArray *selectedServiceMoney;

// 显示数目的中间变量
@property (nonatomic, strong) NSString *showMoneyStr;

// 套餐信息
@property (nonatomic, strong) PackageInfo *packInfo;

// 按钮是否可以被点击
@property (nonatomic, assign) BOOL isClick;

// 全局提交按钮
@property (nonatomic, strong) UIButton *submitBtn;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self isNeedClickBtn];

    returnKeyHandler = [[IQKeyboardReturnKeyHandler alloc] initWithViewController:self];
    
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
        
    [self isNeedClickBtn];
}




- (void)isNeedClickBtn
{
    NSLog(@"kContactAuthenRes==>%@",[[NSUserDefaults standardUserDefaults] boolForKey:kContactAuthenRes] ? @"YES":@"NO");
    NSLog(@"kPersonInfoAuthenRes==>%@",[[NSUserDefaults standardUserDefaults] boolForKey:kPersonInfoAuthenRes] ? @"YES":@"NO");
    NSLog(@"kXinYuAuthenRes==>%@",[[NSUserDefaults standardUserDefaults] boolForKey:kXinYuAuthenRes] ? @"YES":@"NO");
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kContactAuthenRes]
        && [[NSUserDefaults standardUserDefaults] boolForKey:kPersonInfoAuthenRes]
        && [[NSUserDefaults standardUserDefaults] boolForKey:kXinYuAuthenRes])
    {
        self.isClick = YES;
    }
    else
    {
        self.isClick = NO;
    }
    [self.borrowTableView reloadData];
}

- (void)setupUI{
    
    self.navigationItem.title = @"首页";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19.0f],
       NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"]}];
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:68.0f/255.0f green:161.0f/255.0f blue:247.0f/255.0f alpha:1.0f];
    
    self.num1Btn =  [[UIButton alloc] init];
    self.num1Btn.tag = 0;
    [self.num1Btn setTitle:@"额度1500"
                color:mainColor
                 font:mainFont];
    
    self.num2Btn =  [[UIButton alloc] init];
    self.num2Btn.tag = 1;
    [self.num2Btn setTitle:@"额度2000"
                color:[UIColor lightGrayColor]
                 font:mainFont];
    [self.view addSubview:self.num1Btn];
    [self.view addSubview:self.num2Btn];
    [self.num1Btn addTarget:self
                action:@selector(midBtn:)
      forControlEvents:UIControlEventTouchUpInside];
    [self.num2Btn addTarget:self
                action:@selector(midBtn:)
      forControlEvents:UIControlEventTouchUpInside];
    
    [self.num1Btn makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(74.0f);
        make.centerX.equalTo(self.view.mas_centerX).offset(-self.view.frame.size.width/4.0f);
        make.size.mas_equalTo(CGSizeMake(btnW, btnH));
    }];
    
    [self.num2Btn makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.num1Btn.mas_top);
        make.centerX.equalTo(self.view.mas_centerX).offset(self.view.frame.size.width/4.0f);
        make.size.mas_equalTo(CGSizeMake(btnW, btnH));  
    }];
    
    [self.view addSubview:self.borrowTableView];
    [self.borrowTableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.num1Btn.mas_bottom).offset(10.0f);
        make.left.equalTo(self.view.mas_left);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 80.0f));
    }];
    
    
    self.showMoneyStr = @"182";
}

#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (1 == indexPath.section && 0 == indexPath.row)
    {
        return 120.f;
    }
    
    return 60.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        return 2;
    }
    return 15.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (0 == section)
    {
        return [[UIView alloc] init];
    }
    return [[UIView alloc] init];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //return 2;
    if (1 == section) {
        return 1;
    }
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellId"];
        
        if (1 == indexPath.section)
        {
            if (0 == indexPath.row)
            {
                self.submitBtn = [[UIButton alloc] init];
                [cell.contentView addSubview:self.submitBtn];
                [self.submitBtn setTitle:@"提交"
                                   color:mainColor
                                    font:mainFont];
                self.submitBtn.showsTouchWhenHighlighted = YES;
                
                [self.submitBtn addTarget:self
                                   action:@selector(submitData:)
                         forControlEvents:UIControlEventTouchUpInside];
                [self.submitBtn makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(cell.contentView.mas_centerX);
                    make.centerY.equalTo(cell.contentView.mas_centerY); make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width * 3 / 4.0f, 60.0f));
                }];
            }
        }
    }
    
    if (1 == indexPath.section
        && 0 == indexPath.row)
    {
        if (self.isClick)
        {
            self.submitBtn.userInteractionEnabled = YES;//交互关闭
            self.submitBtn.alpha = 1;//透明度
        }
        else
        {
            self.submitBtn.userInteractionEnabled = NO;//交互关闭
            self.submitBtn.alpha = 0.4;//透明度
        }
    }
    
   
    if (0 == indexPath.section)
    {
        if ([self.selectedIndexPath isEqual:indexPath]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            NSLog(@"%@<===>%ld",self.selectedArr[indexPath.row],(long)indexPath.row);
            self.packInfo.periodStr = self.selectedArr[indexPath.row];

        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
                
        cell.textLabel.text = self.selectedArr[indexPath.row];
        
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    self.packInfo.serviceChargeStr = self.showMoneyStr;
    NSLog(@"self.packInfo.serviceChargeStr after:%@",self.showMoneyStr);
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.section)
    {
        if (self.selectedIndexPath)
        {
            UITableViewCell * cell = [tableView cellForRowAtIndexPath:self.selectedIndexPath];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        
        self.selectedIndexPath = indexPath;
    }
    
    self.showMoneyStr = self.selectedServiceMoney[indexPath.row];
    [self.borrowTableView reloadData];
}

#pragma mark - getter、setter
- (PackageInfo *)packInfo
{
    if (!_packInfo)
    {
        _packInfo = [[PackageInfo alloc] init];
        _packInfo.packagesStr = @"1500";
        _packInfo.periodStr = @"7";
        _packInfo.serviceChargeStr = @"182";
        _packInfo.idCardStr = @"";
    }
    return _packInfo;
}

- (NSMutableArray *)num1000Arr
{
    if (!_num1000Arr)
    {
        _num1000Arr = [[NSMutableArray alloc] initWithObjects:@"借款7天",@"借款14天", nil];
    }
    return _num1000Arr;
}

- (NSMutableArray *)num2000Arr
{
    if (!_num2000Arr)
    {
        _num2000Arr = [[NSMutableArray alloc] initWithObjects:@"借款14天",@"借款21天",nil];
    }
    return _num2000Arr;
}

- (NSArray *)serviceMoney1000Arr
{
    if (!_serviceMoney1000Arr)
    {
        _serviceMoney1000Arr = [NSArray arrayWithObjects:@"182",@"150", nil];
    }
    return _serviceMoney1000Arr;
}

- (NSArray *)serviceMoney2000Arr
{
    if (!_serviceMoney2000Arr)
    {
        _serviceMoney2000Arr = [NSArray arrayWithObjects:@"200",@"250", nil];
    }
    return _serviceMoney2000Arr;
}

- (NSArray *)selectedServiceMoney
{
    if (!_selectedServiceMoney)
    {
        _selectedServiceMoney = self.serviceMoney1000Arr;
    }
    return _selectedServiceMoney;
}

- (NSMutableArray *)selectedArr
{
    if (!_selectedArr)
    {
        _selectedArr = self.num1000Arr;
    }
    return _selectedArr;
}

- (NSIndexPath *)selectedIndexPath
{
    if (!_selectedIndexPath)
    {
        _selectedIndexPath =  [NSIndexPath indexPathForRow:0 inSection:0];
    }
    return _selectedIndexPath;
}

- (UITableView *)borrowTableView
{
    if (!_borrowTableView)
    {
        _borrowTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _borrowTableView.delegate = self;
        _borrowTableView.dataSource = self;
        _borrowTableView.scrollEnabled = NO;
        
    }
    
    return _borrowTableView;
}

- (BOOL)isClick
{
    return [self clickRes];
}

- (BOOL)clickRes
{
    NSLog(@"111=%@",[[NSUserDefaults standardUserDefaults] boolForKey:kContactAuthenRes] ? @"YES":@"NO");
     NSLog(@"222=%@",[[NSUserDefaults standardUserDefaults] boolForKey:kPersonInfoAuthenRes] ? @"YES":@"NO");
     NSLog(@"333=%@",[[NSUserDefaults standardUserDefaults] boolForKey:kXinYuAuthenRes] ? @"YES":@"NO");
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kContactAuthenRes]
        && [[NSUserDefaults standardUserDefaults] boolForKey:kPersonInfoAuthenRes]
        && [[NSUserDefaults standardUserDefaults] boolForKey:kXinYuAuthenRes])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


#pragma mark - 提交按钮的点击事件,点击按钮以后所有的数据需要重新初始化
- (void)midBtn:(UIButton *)btn
{
    NSLog(@"btn.isSelected===%@",btn.isSelected ? @"YES":@"NO" );

    // 先判断是哪个按钮
    if (1 == btn.tag)
    {
      // 如果是第二个按钮,再判断选中状态
        [btn setBackgroundColor:mainColor];
        [self.num1Btn setBackgroundColor:[UIColor lightGrayColor]];
        
        self.packInfo.packagesStr = @"2000";
    }
    else
    {
            [btn setBackgroundColor:mainColor];
            [self.num2Btn setBackgroundColor:[UIColor lightGrayColor]];
        self.packInfo.packagesStr = @"1500";
    }

    if (1 == btn.tag)
    {
        self.selectedArr = self.num2000Arr;
        self.selectedServiceMoney = self.serviceMoney2000Arr;

    }
    else
    {
        self.selectedArr = self.num1000Arr;
        self.selectedServiceMoney = self.serviceMoney1000Arr;
    }

    self.selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.showMoneyStr = self.selectedServiceMoney[0];
    
    [self.borrowTableView reloadData];
}



- (void)submitData:(UIButton *)btn
{
    [SVProgressHUD showWithStatus:@"加载中..."];
    HomeService *service = [[HomeService alloc] init];
    NSLog(@"self.packInfo.serviceChargeStr:%@",self.packInfo.serviceChargeStr);
    [service savePackageWithPackages:self.packInfo
                     withCallBack:^(ResObject *resObj) {
                         [SVProgressHUD dismiss];
                         if (resObj.isSuccess)
                         {
                             [SVProgressHUD showSuccessWithStatus:@"提交成功!"];
                             [SVProgressHUD dismissWithDelay:1.0f];
                         }
                         else
                         {
                             [SVProgressHUD showErrorWithStatus:resObj.errMsg];
                             [SVProgressHUD dismissWithDelay:1.0f];
                         }
                     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
